﻿using FFmpeg.NET;
using Serilog;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using VideoTools.Commands;
using VideoTools.Controls;
using Image = System.Drawing.Image;
using MaskPB = VideoTools.Controls.MaskPictureBox;
using MessageBox = System.Windows.MessageBox;
using OpenFileDialog = System.Windows.Forms.OpenFileDialog;
using Path = System.IO.Path;

namespace VideoTools.VideoView
{
    /// <summary>
    /// MargeM3U8Page.xaml 的交互逻辑
    /// </summary>
    public partial class RemoveWatermark2Page : Page, MaskPictureBoxCallback,IDisposable
    {
        private static volatile RemoveWatermark2Page _instance;
        private static object _syncRoot = new object();
        private MaskPB picBox;
        private string picPath;
        private string videoPath;
        private float scale = 1;
        public bool read = false;
        private TimeSpan spendTime;
        private int duration = 0;
        private int durationMilliseconds = 0;
        public double fps;
        private int picCount = 0;



        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool MoveWindow(
            IntPtr hWnd,
            int X,
            int Y,
            int nWidth,
            int nHeight,
            bool bRepaint
        );

        [DllImport("user32.dll")]
        private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

        private RemoveWatermark2Page()
        {
            InitializeComponent();
            InitializeCustomControl();
        }

   
        public static RemoveWatermark2Page Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncRoot)
                    {
                        if (_instance == null)
                        {
                            _instance = new RemoveWatermark2Page();
                        }
                    }
                }
                return _instance;
            }
        }
        

        private void InitializeCustomControl()
        {
            // 创建自定义WinForms控件实例
            picBox = new MaskPB() { Width = 1700, Height = 700 };
            picBox.parent = this;
            picBox.PenWidth = (float)this.PenSlider.Value;

            // 将控件添加到WindowsFormsHost
            winformHost.Child = picBox;
        }

        public void mask_Clear()
        {
            //设置按钮状态
        }

        public void picture_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            //设置按钮状态
        }
        private void ClearMask_Click(object sender, RoutedEventArgs e)
        {
            if (picBox != null )
            {
                System.Drawing.Image image = Bitmap.FromFile(picPath);
                picBox.Image = image;
            }
        }
        private void SaveMask_Click(object sender, RoutedEventArgs e)
        {
            if (picBox != null && picBox.Image != null)
            {
                string path = System.IO.Path.GetDirectoryName(videoPath);
                FileInfo f = new FileInfo(videoPath);
                string tempName = f.Name.Remove(f.Name.LastIndexOf("."));
                string saveFile = path + "\\" + tempName + ".png";
                this.picBox.Save(saveFile, true);
            }
        }
        public void GetVideoInfo()
        {
            Engine ffmpeg = new Engine(@"ffmpeg.exe");
            CancellationToken token = new CancellationToken();
            InputFile inputFile = new InputFile(this.videoPath);
            MetaData data = ffmpeg.GetMetaDataAsync(inputFile, token).GetAwaiter().GetResult();
            if (data == null)
            {
                return;
            }
            int seconds = (int)data.Duration.TotalSeconds;
            duration = seconds;
            if (data.VideoData != null)
            {
                StringBuilder sb = new StringBuilder();
                Random random = new Random();
                TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                fps = data.VideoData.Fps;
                for (int i = 0; i < 10; i++)
                {
                    int index = random.Next(AppConstants.Chars.Length);
                    sb.Append(AppConstants.Chars[index]);
                }
                picPath =
                    "./"
                    + AppConstants.ImageFileStart
                    + Convert.ToInt64(ts.TotalMilliseconds).ToString()
                    + "_"
                    + sb.ToString()
                    + ".jpg";
                var outputFile = new OutputFile(picPath);
                durationMilliseconds = (int)data.Duration.TotalMilliseconds;
                ConversionOptions conversionOptions = new ConversionOptions()
                {
                    Seek = TimeSpan.FromMilliseconds(random.Next(1, durationMilliseconds - 1)),
                };
                ffmpeg
                    .GetThumbnailAsync(inputFile, outputFile, conversionOptions, token)
                    .GetAwaiter()
                    .GetResult();
                System.Drawing.Image image = System.Drawing.Image.FromFile(picPath);
                read = true;
            }
        }

        /// <summary>
        /// 帮助
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="Args"></param>
        public void Help_Click(object Sender, RoutedEventArgs Args)
        {
            MessageBox.Show("首先启动lama-cleaner" +
                "\n命令lama-cleaner --model=lama --device=cuda --port=8080" +
                "\n更多参数lama-cleaner -h，注意端口必须是8080" +
                "\nhttps://github.com/Sanster/IOPaint.git" +
                "\n如未安装使用命令安装pip install lama-cleaner" +
                "\n如果是字幕，请使用video-subtitle-remover（vsr）");
        }
        /// <summary>
        /// 清理缓存
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="Args"></param>
        public void ClearCache_Click(object Sender, RoutedEventArgs Args)
        {
            DirectoryInfo di = null;
            di = new DirectoryInfo(AppConstants.CachePath);
            if (di.Exists)
            {
                FileInfo[] fileInfos = di.GetFiles();
                foreach (var item in fileInfos)
                {
                    item.Delete();
                }
            }

            di = new DirectoryInfo(AppConstants.InPath);
            if (di.Exists)
            {
                di.Delete(true);
            }
            di.Create();
            di = new DirectoryInfo(AppConstants.OutPath);
            if (di.Exists)
            {
                di.Delete(true);
            }
            di.Create();
            this.ResetThumbnailButton.IsEnabled = true;
            this.ResetThumbnailButton.IsEnabled = true;
            this.ClearMaskButton.IsEnabled = true;
            this.SaveMaskButton.IsEnabled = true;
            this.SplitAudioButton.IsEnabled = true;
            this.SplitFrameButton.IsEnabled = true;
            this.RemoveWaterMarkButton.IsEnabled = true;
            this.MergeAudioButton.IsEnabled = true;
            this.MergeFrameButton.IsEnabled = true;
        }
        /// <summary>
        /// 合并音频
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="Args"></param>
        public void MergeAudio_Click(object Sender, RoutedEventArgs Args)
        {
            Image mask = this.picBox.getMaskImage(true);
            if (mask == null)
            {
                return;
            }
            this.picBox.Save(Directory.GetCurrentDirectory() + "/cache/mask.png", true);
            if (read == false) return;
            string path = Path.GetDirectoryName(videoPath);
            FileInfo f = new FileInfo(videoPath);
            string tempName = f.Name.Remove(f.Name.LastIndexOf("."));

            Process process = new Process();
            process.StartInfo.FileName = "ffmpeg";
            process.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
            //ffmpeg -i ./temp/video_cleaned.mp4 -i ./temp/audio.$codec -c:v copy -map 0:v -map 1:a -y ./output/video_final.mp4 
            string param = "-i \"cache/video.mp4\" -i \"cache/audio.aac\" -c:v copy -map 0:v -map 1:a -y \"" + path + "\\" + tempName + AppConstants.WaterMark2 + ".mp4\" -y";
            Log.Debug("合并参数 ffmpeg " + param);
            process.StartInfo.Arguments = param;
            process.StartInfo.CreateNoWindow = true;//显示命令行窗口
                                                    //不使用操作系统使用的shell启动进程
            process.StartInfo.UseShellExecute = false;
            //将输出信息重定向
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.EnableRaisingEvents = true;

            process.OutputDataReceived += (o, e) => Log.Information(e.Data ?? "NULL", e.Data);
            process.ErrorDataReceived += (o, e) => Log.Information(e.Data ?? "NULL", e.Data);
            process.Exited += (o, e) => Log.Information("Exited", "ffplay");

            process.Start();
            //开始异步读取输出
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            this.ResetThumbnailButton.IsEnabled = true;
            this.ClearMaskButton.IsEnabled = true;
            this.SaveMaskButton.IsEnabled = true;
            this.SplitAudioButton.IsEnabled = true;
            this.SplitFrameButton.IsEnabled = true;
            this.RemoveWaterMarkButton.IsEnabled = true;
            this.MergeAudioButton.IsEnabled = true;
            this.MergeFrameButton.IsEnabled = true;
        }
        /// <summary>
        /// 合并每帧
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="Args"></param>
        public void MergeFrame_Click(object Sender, RoutedEventArgs Args)
        {
            Image mask = this.picBox.getMaskImage(true);
            if (mask == null)
            {
                return;
            }
            if (read == false) return;
            string path = Path.GetDirectoryName(videoPath);
            FileInfo f = new FileInfo(videoPath);
            spendTime = new TimeSpan(DateTime.Now.Ticks);

            string tempName = f.Name.Remove(f.Name.LastIndexOf("."));

            Process process = new Process();
            process.StartInfo.FileName = "ffmpeg";
            process.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
            // -i #{input} -y -f image2 d:/outputs/%5d.jpg
            //ffmpeg -framerate 30 -i cache/input/%6d.jpg -c:v libx264 -crf 7 -pix_fmt yuv420p -y cache/video_cleaned.mp4
            string param = "-framerate " + fps + " -i \"cache/output/%6d.jpg\" -c:v libx264 -crf 7 -pix_fmt yuv420p -y \"cache/video.mp4\"";

            Log.Debug("合并每帧参数 ffmpeg " + param);
            process.StartInfo.Arguments = param;
            process.StartInfo.CreateNoWindow = true;//显示命令行窗口
                                                    //不使用操作系统使用的shell启动进程
            process.StartInfo.UseShellExecute = false;
            //将输出信息重定向
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.EnableRaisingEvents = true;
            this.MergeFrameButton.IsEnabled = false;
            this.MergeFrameButton.Content = "合并每帧中";
            process.Exited += new EventHandler(mergeFrame_Exited);
            process.OutputDataReceived += new DataReceivedEventHandler(mergeFrame_OutputDataReceived);
            process.ErrorDataReceived += new DataReceivedEventHandler(mergeFrame_ErrorDataReceived);

            process.Start();
            //开始异步读取输出
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            this.ResetThumbnailButton.IsEnabled = true;
            this.ClearMaskButton.IsEnabled = true;
            this.SaveMaskButton.IsEnabled = true;
            this.SplitAudioButton.IsEnabled = true;
            this.SplitFrameButton.IsEnabled = true;
            this.RemoveWaterMarkButton.IsEnabled = true;
            this.MergeAudioButton.IsEnabled = false;
            this.MergeFrameButton.IsEnabled = false;

        }

        void mergeFrame_OutputDataReceived(Object sender, DataReceivedEventArgs e)
        {
        }
        void mergeFrame_Exited(Object sender, EventArgs e)
        {
            RemoveWatermark2Commands.Instance.SpendTimeVisibility = Visibility.Hidden;
            RemoveWatermark2Commands.Instance.ProgressVisibility = Visibility.Hidden;
            Dispatcher.Invoke(() => {
                this.MergeFrameButton.Content = "4.合并每帧";
                this.ResetThumbnailButton.IsEnabled = true;
                this.ClearMaskButton.IsEnabled = true;
                this.SaveMaskButton.IsEnabled = true;
                this.SplitAudioButton.IsEnabled = true;
                this.SplitFrameButton.IsEnabled = true;
                this.RemoveWaterMarkButton.IsEnabled = true;
                this.MergeAudioButton.IsEnabled = true;
                this.MergeFrameButton.IsEnabled = true;
            });

        }
        void mergeFrame_ErrorDataReceived(Object sender, DataReceivedEventArgs e)
        {
            //这里得到的是错误信息
            string info = e.Data;
            if (info != null && info.Contains("frame") && info.Contains("fps") && info.Contains("time") && info.Contains("bitrate") && info.Contains("speed"))
            {
                //frame= 5721 fps=315 q=24.8 Lsize=N/A time=00:03:58.33 bitrate=N/A dup=1 drop=92 speed=13.1x
                //string s = "frame= 2700 fps=178 q=26.0 size=   15616kB time=00:01:31.90 bitrate=1391.9kbits/s speed=6.07x";
                string r = "^frame.+time=(.+)bitrate=.+";
                Match match = Regex.Match(info, r);
                if (match.Success)
                {
                    string time = match.Groups[1].Value;
                    if (time.Contains("-"))
                    {
                        return;
                    }
                    if (time.Contains("."))
                    {
                        time = time.Split(".")[0];
                    }
                    string[] times = time.Split(":");
                    int cur = int.Parse(times[0]) * 60 * 60 + int.Parse(times[1]) * 60 + int.Parse(times[2]);

                    double rx = Math.Round((Convert.ToDouble(cur) / Convert.ToDouble(duration)), 2);
                    RemoveWatermark2Commands.Instance.Progress = rx;
                    RemoveWatermark2Commands.Instance.SpendTime = new TimeSpan(spendTime.Ticks - DateTime.Now.Ticks);
                    RemoveWatermark2Commands.Instance.SpendTimeVisibility = Visibility.Visible;
                    RemoveWatermark2Commands.Instance.ProgressVisibility = Visibility.Visible;
                }
            }
        }

        public void RemoveWaterMark_Click(object Sender, RoutedEventArgs Args)
        {
            Image mask = this.picBox.getMaskImage(true);
            if (mask == null)
            {
                return;
            }
            if (read == false) return;
            string path = Path.GetDirectoryName(videoPath);
            FileInfo f = new FileInfo(videoPath);
            spendTime = new TimeSpan(DateTime.Now.Ticks);

            string tempName = f.Name.Remove(f.Name.LastIndexOf("."));

            Process process = new Process();
            process.StartInfo.FileName = "python";
            string param = "clear.py";
            Log.Information("python " + param);
            process.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
            // -i #{input} -y -f image2 d:/outputs/%5d.jpg

            Log.Debug("清理水印 ffmpeg " + param);
            process.StartInfo.Arguments = param;
            process.StartInfo.CreateNoWindow = true;//显示命令行窗口
                                                    //不使用操作系统使用的shell启动进程
            process.StartInfo.UseShellExecute = false;
            //将输出信息重定向
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.EnableRaisingEvents = true;
            this.RemoveWaterMarkButton.IsEnabled = false;
            process.Exited += new EventHandler(RemoveWaterMark_Exited);
            process.OutputDataReceived += new DataReceivedEventHandler(RemoveWaterMark_OutputDataReceived);
            process.ErrorDataReceived += new DataReceivedEventHandler(RemoveWaterMark_ErrorDataReceived);

            process.Start();
            //开始异步读取输出
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            this.ResetThumbnailButton.IsEnabled = true;
            this.ClearMaskButton.IsEnabled = true;
            this.SaveMaskButton.IsEnabled = true;
            this.SplitAudioButton.IsEnabled = true;
            this.SplitFrameButton.IsEnabled = true;
            this.RemoveWaterMarkButton.IsEnabled = false;
            this.MergeAudioButton.IsEnabled = false;
            this.MergeFrameButton.IsEnabled = false;
        }
        void RemoveWaterMark_Exited(Object sender, EventArgs e)
        {
            RemoveWatermark2Commands.Instance.SpendTimeVisibility = Visibility.Hidden;
            RemoveWatermark2Commands.Instance.ProgressVisibility = Visibility.Hidden;
        }
        void RemoveWaterMark_ErrorDataReceived(Object sender, DataReceivedEventArgs e)
        {
            Log.Information("error " + e.Data);
        }

        void RemoveWaterMark_OutputDataReceived(Object sender, DataReceivedEventArgs e)
        {
            string data = e.Data;
            Log.Information("outputx " + data + "\t" + (data == null));
            if (data != null)
            {
                Log.Information("output " + data + "\t" + data.Contains("index="));
                if (data.Contains("doneall"))
                {
                    Dispatcher.Invoke(() =>
                    {
                        this.RemoveWaterMarkButton.IsEnabled = true;
                        this.RemoveWaterMarkButton.Content = "3.处理每帧";

                        this.ResetThumbnailButton.IsEnabled = true;
                        this.ClearMaskButton.IsEnabled = true;
                        this.SaveMaskButton.IsEnabled = true;
                        this.SplitAudioButton.IsEnabled = true;
                        this.SplitFrameButton.IsEnabled = true;
                        this.RemoveWaterMarkButton.IsEnabled = true;
                        this.MergeAudioButton.IsEnabled = true;
                        this.MergeFrameButton.IsEnabled = true;
                    });
                }
                else if (data.Contains("index="))
                {
                    Dispatcher.Invoke(() =>
                    {
                        string t = data.Replace("index=", "");
                        this.RemoveWaterMarkButton.Content = t;
                        string[] infos = t.Split("/");
                        int index = int.Parse(infos[0]);
                        int count = int.Parse(infos[1]);
                        RemoveWatermark2Commands.Instance.Progress = (double)index / (double)count;
                        RemoveWatermark2Commands.Instance.SpendTime = new TimeSpan(spendTime.Ticks - DateTime.Now.Ticks);
                        RemoveWatermark2Commands.Instance.SpendTimeVisibility = Visibility.Visible;
                        RemoveWatermark2Commands.Instance.ProgressVisibility = Visibility.Visible;
                    });

                }
            }
        }
        /// <summary>
        /// 分离每帧
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="Args"></param>
        public void SplitFrame_Click(object Sender, RoutedEventArgs Args)
        {
            System.Drawing.Image mask = this.picBox.getMaskImage(true);
            if (mask == null)
            {
                return;
            }
            if (read == false) return;
            string path = Path.GetDirectoryName(videoPath);
            FileInfo f = new FileInfo(videoPath);
            spendTime = new TimeSpan(DateTime.Now.Ticks);

            string tempName = f.Name.Remove(f.Name.LastIndexOf("."));
            Process process = new Process();
            process.StartInfo.FileName = "ffmpeg";
            process.StartInfo.WorkingDirectory = path;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
            // -i #{input} -y -f image2 d:/outputs/%5d.jpg
            string param = "-i \"" + videoPath + "\" -y -f image2 \"" + AppConstants.InPath + "/%6d.jpg\"";

            Log.Debug("分离每帧参数 ffmpeg " + param);
            process.StartInfo.Arguments = param;
            process.StartInfo.CreateNoWindow = true;//显示命令行窗口
                                                    //不使用操作系统使用的shell启动进程
            process.StartInfo.UseShellExecute = false;
            //将输出信息重定向
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.EnableRaisingEvents = true;
            this.SplitFrameButton.IsEnabled = false;
            this.SplitFrameButton.Content = "分离每帧中";
            process.Exited += new EventHandler(splitFrame_Exited);
            process.OutputDataReceived += new DataReceivedEventHandler(splitFrame_OutputDataReceived);
            process.ErrorDataReceived += new DataReceivedEventHandler(splitFrame_ErrorDataReceived);

            process.Start();
            //开始异步读取输出
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            this.ResetThumbnailButton.IsEnabled = true;
            this.ClearMaskButton.IsEnabled = true;
            this.SaveMaskButton.IsEnabled = true;
            this.SplitAudioButton.IsEnabled = true;
            this.SplitFrameButton.IsEnabled = true;
            this.RemoveWaterMarkButton.IsEnabled = false;
            this.MergeAudioButton.IsEnabled = false;
            this.MergeFrameButton.IsEnabled = false;
        
        }
        void splitFrame_OutputDataReceived(Object sender, DataReceivedEventArgs e)
        {
        }

        void splitFrame_Exited(Object sender, EventArgs e)
        {
            RemoveWatermark2Commands.Instance.SpendTimeVisibility = Visibility.Hidden;
            RemoveWatermark2Commands.Instance.ProgressVisibility = Visibility.Hidden;
            Dispatcher.Invoke(() => {
                this.SplitFrameButton.Content = "2.分离每帧";
                this.ResetThumbnailButton.IsEnabled = true;
                this.ClearMaskButton.IsEnabled = true;
                this.SaveMaskButton.IsEnabled = true;
                this.SplitAudioButton.IsEnabled = true;
                this.SplitFrameButton.IsEnabled = true;
                this.RemoveWaterMarkButton.IsEnabled = true;
                this.MergeAudioButton.IsEnabled = false;
                this.MergeFrameButton.IsEnabled = false;
            });

            picCount = Directory.GetFiles(AppConstants.InPath).Length;

        }
        void splitFrame_ErrorDataReceived(Object sender, DataReceivedEventArgs e)
        {
            //这里得到的是错误信息
            string info = e.Data;
            if (info != null && info.Contains("frame") && info.Contains("fps") && info.Contains("time") && info.Contains("bitrate") && info.Contains("speed"))
            {
                string r = "^frame.+time=(.+)bitrate=.+";
                Match match = Regex.Match(info, r);
                if (match.Success)
                {
                    string time = match.Groups[1].Value;
                    if (time.Contains("."))
                    {
                        time = time.Split(".")[0];
                    }
                    string[] times = time.Split(":");
                    int cur = int.Parse(times[0]) * 60 * 60 + int.Parse(times[1]) * 60 + int.Parse(times[2]);
                    double rx = Math.Round((Convert.ToDouble(cur) / Convert.ToDouble(duration)), 2);
                    RemoveWatermark2Commands.Instance.Progress = rx;
                    RemoveWatermark2Commands.Instance.SpendTime = new TimeSpan(spendTime.Ticks - DateTime.Now.Ticks);
                    RemoveWatermark2Commands.Instance.SpendTimeVisibility = Visibility.Visible;
                    RemoveWatermark2Commands.Instance.ProgressVisibility = Visibility.Visible;
                }
            }
        }
        /// <summary>
        /// 分离音频
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="Args"></param>
        public void SplitAudio_Click(object Sender, RoutedEventArgs Args)
        {
            System.Drawing.Image mask = this.picBox.getMaskImage(true);
            if (mask == null)
            {
                //还没有绘制遮罩
                return;
            }
            this.picBox.Save(Directory.GetCurrentDirectory() + "/cache/mask.png", true);
            if (read == false) return;
            string path = System.IO.Path.GetDirectoryName(videoPath);
            FileInfo f = new FileInfo(videoPath);

            Process process = new Process();
            process.StartInfo.FileName = "ffmpeg";
            process.StartInfo.WorkingDirectory = path;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

            string param = "-i \"" + videoPath + "\" -vn -acodec copy \"" + Directory.GetCurrentDirectory() + "/cache/audio.aac\" -y";
            process.StartInfo.Arguments = param;
            process.StartInfo.CreateNoWindow = true;//显示命令行窗口
                                                    //不使用操作系统使用的shell启动进程
            process.StartInfo.UseShellExecute = false;
            //将输出信息重定向
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.EnableRaisingEvents = true;

            process.OutputDataReceived += (o, e) => { };
            process.ErrorDataReceived += (o, e) => { };
            process.Exited += (o, e) => { };

            process.Start();
            //开始异步读取输出
            process.BeginOutputReadLine();
            process.BeginErrorReadLine();
            

            this.ResetThumbnailButton.IsEnabled = true;
            this.ClearMaskButton.IsEnabled = true;
            this.SaveMaskButton.IsEnabled = true;
            this.SplitAudioButton.IsEnabled = true;
            this.SplitFrameButton.IsEnabled = true;
            this.RemoveWaterMarkButton.IsEnabled = false;
            this.MergeAudioButton.IsEnabled = false;
            this.MergeFrameButton.IsEnabled = false;
            process.WaitForExit();
        }
        
       

       
        async void ResetPicbox_Click(object Sender, RoutedEventArgs Args)
        {
            GetVideoInfo();
            Image image = Bitmap.FromFile(picPath);
            picBox.Image = image;
            int maxWidth = 1280;
            int w = image.Width;
            int h = image.Height;
            scale = (float)maxWidth / (float)w;
            int w1 = maxWidth;
            int h1 = (int)(h * scale);

            winformHost.Width = w1;
            winformHost.Height = h1;

            winformDock.Height = winformHost.Height;
            winformDock.Width = winformHost.Width;
            picBox.Focus();

            ClearCache_Click(null,null);
        }
        private void OpenVideo_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            string filter = "视频文件(*.mp4)|*.mp4";
            openFileDialog.Filter = filter;
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.videoPath = openFileDialog.FileName;
                this.ResetPicbox_Click(null, null);
            }
            else
            {
                return;
            }
        }


        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (picBox != null)
            {
                this.picBox.PenWidth = (float)e.NewValue;
            }
        }

        public void Dispose()
        {
            ClearCache_Click(null,null);
        }
    }
}
